#pragma once

#include <iostream>
#include <string>
#include <cstring>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <pthread.h>
#include <functional>
#include "log.hpp"
#include "Protocol.hpp"

static const uint16_t gport = 8080;
static const int gbacklog = 5;

namespace server
{
    class CalServer;

    class ThreadData
    {
    public:
        ThreadData(CalServer *self, int sock) : _self(self), _sock(sock)
        {
        }
        CalServer *_self;
        int _sock;
    };

    typedef std::function<void(const Request &, Response &)> func_t;
    // 保证解耦
    void handlerEntery(int sock, func_t func)
    {
        std::string inbuffer;
        while (true)
        {
            // 1. 读取
            std::string req_text, req_str;
            if (!recvPackage(sock, inbuffer, &req_text))
                return; // "x op y" -> "content_lin"\r\n"x op y"
            std::cout << "带报头: \n" << req_text << std::endl;
            if (!deLength(req_text, &req_str))
                return;
            std::cout << "去报头: \n" << req_str << std::endl;
            // 2. 反序列化
            // 2.1 得到一个结构化的请求对象
            Request req;
            if (!req.deserialize(req_str))
                return;

            // 3 计算机处理
            // 3.1 得到一个结构化的响应
            Response resp;
            func(req, resp); // 处理结果放进resp里面了

            // 4. 对响应Respose, 进行序列化
            // 4.1 得到了一个"字符串"
            std::string resp_str;
            resp.serialize(&resp_str);
            std::cout << "计算完成, 序列化响应: " << resp_str << std::endl;

            // 5. 然后再发送响应
            // 5.1 构建成一个完整的报文
            std::string send_string = enLength(resp_str);
            std::cout << "构建完成完整的响应: \n" << send_string << std::endl;
            // "exitcode result" -> "content_lin"\r\n"exitcode result"
            send(sock, send_string.c_str(), send_string.size(), 0); // bug ?}
        }
    }
    class CalServer
    {
        enum
        {
            USAGE_ERR = 1,
            SOCK_ERR,
            BIND_ERR,
            LISTEN_ERR
        };

    public:
        CalServer(const uint16_t &port = gport) : _listensock(-1), _port(port)
        {
        }
        void initServer()
        {
            // signal(SIGCHLD, SIG_IGN); 
            // 1. 创建套接字
            _listensock = socket(AF_INET, SOCK_STREAM, 0);
            if (_listensock == -1)
            {
                logMessage(FATAL, "create socket error");
                exit(SOCK_ERR);
            }
            logMessage(NORMAL, "create socket success");

            // 2.绑定自己的网络信息
            struct sockaddr_in local;
            memset(&local, 0, sizeof(local));
            local.sin_family = AF_INET;
            local.sin_port = htons(_port);
            local.sin_addr.s_addr = INADDR_ANY;
            if (bind(_listensock, (struct sockaddr *)&local, sizeof(local)) < 0)
            {
                logMessage(FATAL, "bind socket error");
                exit(BIND_ERR);
            }
            logMessage(NORMAL, "bind socket success");

            // 3. 设置socket 为监听状态
            if (listen(_listensock, gbacklog) < 0) // gbacklog后面再学
            {
                logMessage(FATAL, "listen socket error");
                exit(LISTEN_ERR);
            }
            logMessage(NORMAL, "listen socket success: %d", _listensock);
        }
        void start(func_t func)
        {
            for (;;)
            {
                // 4. 获取新链接
                // sock, 和client进行通信的fd
                struct sockaddr_in peer;
                socklen_t len = sizeof(peer);
                int sock = accept(_listensock, (struct sockaddr *)&peer, &len);
                if (sock < 0)
                {
                    logMessage(ERROR, "accept error, next");
                    continue;
                }
                logMessage(NORMAL, "accept a new link success, get a new sock: %d", sock);

                // version 2 // 多进程版(2)
                pid_t id = fork();
                if (id == 0)
                {
                    // 关闭不需要的文件描述符
                    close(_listensock);
                    if(fork() > 0) exit(0);
                    handlerEntery(sock, func);
                    close(sock);
                    exit(0);
                }
                // father
                pid_t ret = waitpid(id, nullptr, 0);
                if (ret > 0)
                {
                    logMessage(NORMAL, "wait child sucess: "); // ?
                }
            }
        }
        ~CalServer()
        {
        }

    private:
        int _listensock; // 不是用来通信的, 而是用来监听链接的, 获取新链接
        uint16_t _port;
    };
};
